package com.front.web.lvyou_specialty_front;

import com.alibaba.fastjson.JSON;
import com.bootdo.common.redisUtils.JedisUtils;
import com.bootdo.common.utils.*;
import com.bootdo.common.wxpay.MD5Util;
import com.bootdo.lvyou.domain.XcxConfig;
import com.bootdo.lvyou_specialty.domain.LvyouSpecialtyGzhConfig;
import com.bootdo.lvyou_specialty.domain.LvyouSpecialtyMerchant;
import com.bootdo.lvyou_specialty.service.LvyouSpecialtyGzhConfigService;
import com.bootdo.lvyou_specialty.service.LvyouSpecialtyMerchantService;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.UserService;
import com.bootdo.wx.domain.Config;
import com.front.web.lvyou_specialty_front.pagevo.AccessToken;
import com.front.web.lvyou_specialty_front.util.AesException;
import com.front.web.lvyou_specialty_front.util.SHA1;
import com.front.web.lvyou_specialty_front.util.SendMbMessageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/f/gzhConfigController")
public class GZHConfigController {

    private static String wxGetTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";

    @Autowired
    private UserService userService;

    @Autowired
    private LvyouSpecialtyMerchantService lvyouSpecialtyMerchantService;

    @Autowired
    private LvyouSpecialtyGzhConfigService lvyouSpecialtyGzhConfigService;

    /**
     * http://lvyou.lxjhua.work/f/gzhConfigController/toPage
     */
    @RequestMapping("toPage")
    public String toPage(@RequestParam("code")String code,
                         @RequestParam("state")Long state) {

        LvyouSpecialtyGzhConfig aDefault = lvyouSpecialtyGzhConfigService.getDefault();

        // 拿到code，拿到供应商的id（state）
        // 得到供应商的信息
        LvyouSpecialtyMerchant lvyouSpecialtyMerchant = lvyouSpecialtyMerchantService.get(state);
        if (lvyouSpecialtyMerchant == null) {
            return "lvyou_specialty/lvyouSpecialtyGzhConfig/bangdingErr";
        }

        Map<String, Object> param = new HashMap<>();
        param.put("appid", aDefault.getAppId());
        param.put("secret", aDefault.getAppsecret());
        param.put("code", code);
        param.put("grant_type", "authorization_code");

//        String lvyou_wx_accessToken = JedisUtils.get(MD5Utils.encrypt("lvyou_wx_accessToken"));
        AccessToken accessToken = null;
        try {
            String result = HttpUtil.doPost(wxGetTokenUrl, param);
            accessToken = JSON.parseObject(result, AccessToken.class);
            if (accessToken.getErrcode() != null) {
                return "lvyou_specialty/lvyouSpecialtyGzhConfig/bangdingErr";
            }

            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("出现了异常");
            return "lvyou_specialty/lvyouSpecialtyGzhConfig/bangdingErr";
        }

        // 通过code获取access_token以及openid
        // 保存到数据库
        UserDO userDO = userService.getByMerchantId(state);
        userDO.setWxGzhOpenId(accessToken.getOpenid());
        userService.updateByMercahntId(accessToken.getOpenid(), state);

        return "lvyou_specialty/lvyouSpecialtyGzhConfig/bangdingSuccess";

    }

    /**
     * http://192.168.0.239/f/gzhConfigController/backNotification
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/backNotification")
    public void backNotification(HttpServletRequest request,
                                 @RequestParam()Map<String, String> paramMap,
                                 HttpServletResponse response) throws Exception {

        String signature = paramMap.get("signature");
        String timestamp = paramMap.get("timestamp");
        String nonce = paramMap.get("nonce");
        String echostr = paramMap.get("echostr");
        String token = paramMap.get("Token");
        PrintWriter writer = response.getWriter();

        if (!testWxSign(paramMap)) {
            return;
        }
        if (StringUtils.isNotEmpty(echostr)) {
            writer.write(echostr);
            writer.close();
            return;
        }

    }

    /**
     * http://192.168.0.239/f/gzhConfigController/getUserImageNew
     * @param response
     * @throws Exception
     */
    @RequestMapping("/getUserImageNew")
    public void getOrderQrcode(HttpServletResponse response) throws Exception {

        // 得到用户信息
        UserDO user = ShiroUtils.getUser();
        if (user == null) {
            return;
        }
        UserDO userDO = userService.get(ShiroUtils.getUserId());
        if (userDO == null) {
            return;
        }

        // 得到公众号的配置信息
        List<LvyouSpecialtyGzhConfig> list = lvyouSpecialtyGzhConfigService.list(new HashMap<>());
        if (list.size() == 0) {
            return;
        }
        System.out.println("用户的id" + userDO.getMerchantId());
        String url = URLEncoder.encode(list.get(0).getRedirectUrl() + userDO.getMerchantId(), "utf-8");

        BufferedImage qr = QrcodeUtils.getBarCodeImgByUrl(url,640,640);
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ImageIO.write(qr, "jpg", response.getOutputStream());
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

    @RequestMapping("/testBack")
    public void testBack(HttpServletResponse response) throws Exception {

        UserDO userDO = userService.getByMerchantId(14L);
        Config config = new Config();
        LvyouSpecialtyGzhConfig defalt = lvyouSpecialtyGzhConfigService.getDefault();
        config.setWxAppId(defalt.getAppId());
        config.setWxAppSecret(defalt.getAppsecret());
        SendMbMessageUtils.sendUserDefaultTempMessage(userDO, config, defalt.getMessageRedirectUrl());
    }

    // 验证签名
    private boolean testWxSign(Map<String, String>paramMap) {
        String signature = paramMap.get("signature");
        String timestamp = paramMap.get("timestamp");
        String nonce = paramMap.get("nonce");
        String token = paramMap.get("Token");

        String sha11 = null;
        try {
            sha11 = SHA1.getSHA1(token, timestamp, nonce, "");
            if (StringUtils.equals(sha11, signature)) {
                return true;
            }
        } catch (AesException e) {
            e.printStackTrace();
        }
        return false;
    }

    @RequestMapping("success")
    public String success() {
        return "lvyou_specialty/lvyouSpecialtyGzhConfig/bangdingSuccess";
    }
    @RequestMapping("err")
    public String err() {
        return "lvyou_specialty/lvyouSpecialtyGzhConfig/bangdingErr";
    }

}
